package com.iscc.fake.controller;

import com.google.gson.Gson;
import com.iscc.fake.service.Impl.ProductServiceImpl;
import com.iscc.fake.service.ProductService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet({"/queryForm.do"})
public class QueryFormServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ProductService productService = new ProductServiceImpl();
        PrintWriter out = response.getWriter();
        Gson gson = new Gson();
        String uri = request.getRequestURI();
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> resultMap = new HashMap<>();
        if (uri.endsWith("/queryForm.do")) {
            String name = request.getParameter("pname");
            list = productService.queryForm(name);
        }
        if (list.size() > 0) {
            resultMap.put("code", 200);
            resultMap.put("msg", "查询商品成功");
            resultMap.put("result", list);
        } else {
            resultMap.put("code", 201);
            resultMap.put("msg", "查询商品成功,暂无数据");
        }
        String resultStr = gson.toJson(resultMap);
        out.print(resultStr);
    }
}
